<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use app\admin\model\User;
use app\common\controller\Backend;
use app\common\model\Attachment;
use app\common\model\Order;
use app\common\model\user\Appoints;
use fast\Date;
use think\Db;
use think\Model;

/**
 * 控制台
 *
 * @icon   fa fa-dashboard
 * @remark 用于展示当前系统中的统计数据、统计报表及重要实时数据
 */
class Dashboard extends Backend
{

    /**
     * 查看
     */
    public function index()
    {
        try {
            \think\Db::execute("SET @@sql_mode='';");
        } catch (\Exception $e) {

        }
        $column = [];
        $starttime = Date::unixtime('day', -6);
        $endtime = Date::unixtime('day', 0, 'end');
        $joinlist = Db("user")->where('jointime', 'between time', [$starttime, $endtime])
            ->field('jointime, status, COUNT(*) AS nums, DATE_FORMAT(FROM_UNIXTIME(jointime), "%Y-%m-%d") AS join_date')
            ->group('join_date')
            ->select();
        for ($time = $starttime; $time <= $endtime;) {
            $column[] = date("Y-m-d", $time);
            $time += 86400;
        }
        $userlist = array_fill_keys($column, 0);
        foreach ($joinlist as $k => $v) {
            $userlist[$v['join_date']] = $v['nums'];
        }

        $dbTableList = Db::query("SHOW TABLE STATUS");
        $addonList = get_addon_list();
        $totalworkingaddon = 0;
        $totaladdon = count($addonList);
        foreach ($addonList as $index => $item) {
            if ($item['state']) {
                $totalworkingaddon += 1;
            }
        }
        $this->view->assign([
            'totaluser'         => User::count(),
            'totaladdon'        => $totaladdon,
            'totaladmin'        => Admin::count(),
            'totalmoney'=>Order::where(['status'=>['>',0]])->sum('total_fee'),
            'totalcategory'     => \app\common\model\Category::count(),
            'todayusersignup'   => User::whereTime('jointime', 'today')->count(),
            'todayuserlogin'    => User::whereTime('logintime', 'today')->count(),
            'sevendau'          => User::whereTime('jointime|logintime|prevtime', '-7 days')->count(),
            'thirtydau'         => User::whereTime('jointime|logintime|prevtime', '-30 days')->count(),
            'threednu'          => User::whereTime('jointime', '-3 days')->count(),
            'sevendnu'          => User::whereTime('jointime', '-7 days')->count(),
            'dbtablenums'       => count($dbTableList),
            'dbsize'            => array_sum(array_map(function ($item) {
                return $item['Data_length'] + $item['Index_length'];
            }, $dbTableList)),
            'totalworkingaddon' => $totalworkingaddon,
            'attachmentnums'    => Attachment::count(),
            'attachmentsize'    => Attachment::sum('filesize'),
            'picturenums'       => Attachment::where('mimetype', 'like', 'image/%')->count(),
            'picturesize'       => Attachment::where('mimetype', 'like', 'image/%')->sum('filesize'),
        ]);

        $this->assignconfig('column', array_keys($userlist));
        $this->assignconfig('userdata', array_values($userlist));

        return $this->view->fetch();
    }
    /**
     * 查看折线图
     */
    public function circle()
    {

       // $this->request->isPost()=true;
        error_reporting(E_ERROR | E_WARNING | E_PARSE);

        if (true) {
            $startdate = input('startdate','');
            $order_type = input('type');
            if (!$startdate) {
                $startdate = date("Y-m-d 00:00:00", \fast\Date::unixtime('day', -7)) . ' - ' . date('Y-m-d 23:59:59');
            }

            //
            $is_has_data = false;
            // 判断的where条件、group的时间字段、field数据
            $need_handle_data = [];
            $need_handle_field = ['count'];
            switch ($order_type) {

                case 'orders':
                    $is_has_data = true;
                    $need_handle_field = ['total_price'];
                    $need_handle_data = [
                        [
                            'db' => new \app\common\model\order\Order(),
                            'whereData' => [
                                'pay_status' => 20,
                                'refund_status'=>['>',0]
                            ],
                            'groupTime' => [
                                'name' => 'createtime',
                                'type' => 'int',
                            ],
                            'fieldData' => ['sum(total_fee) AS total_price'],
                            'fieldDataText' => ['订单金额'],
                        ],
                    ];
                    break;
                case 'user':
                    $is_has_data = true;
                    $need_handle_field = ['count'];
                    $need_handle_data = [
                        [
                            'db' => (new \app\common\model\User()),
                            'whereData' => [

                            ],
                            'groupTime' => [
                                'name' => 'createtime',
                                'type' => 'int',
                            ],
                            'fieldData' => ['count(*) AS count'],
                            'fieldDataText' => ['注册用户'],
                        ],
                    ];
                    break;
                case 'appoints':
                    $is_has_data = true;
                    $need_handle_field = ['count1'];
                    $need_handle_data = [
                        [
                            'db' => (new Appoints()),
                            'whereData' => [
                               'status'=>['in',[0,1]]
                            ],
                            'groupTime' => [
                                'name' => 'createtime',
                                'type' => 'int',
                            ],
                            'fieldData' => ['count(*) AS count1'],
                            'fieldDataText' => ['预约数量'],
                        ],
                    ];
                    break;
                default:
                    $result = array("series" => [], 'column' => []);
                    break;
            }
            if ($is_has_data) {
                $type = 'day';
                list($start, $end) = explode(' - ', $startdate);
                $starttime = strtotime($start);
                $endtime = strtotime($end);
                if ($endtime - $starttime >= 86400 * 30 * 2) {
                    $type = 'month';
                } else if ($endtime - $starttime <= 86400) {
                    $type = 'hour';
                }
                if ($type == 'month') {
                    //按月构造数据
                    $starttime = strtotime('last month', $starttime);
                    while (($starttime = strtotime('next month', $starttime)) <= $endtime) {
                        $column[] = date('Y-m', $starttime);
                    }
                } else if ($type == 'hour') {
                    for ($time = $starttime; $time <= $endtime;) {
                        $column[] = date("Y-m-d H点", $time);
                        $time += 3600;
                    }
                } else {
                    //按天构造数据
                    for ($time = $starttime; $time <= $endtime;) {
                        $column[] = date("Y-m-d", $time);
                        $time += 86400;
                    }
                }
                $list = array_fill_keys($column, 0);
                $fieldtextdata = [];
                foreach ($need_handle_data as $key => $value) {
                    foreach ($need_handle_field as $k => $v) {
                        $series[$v . '_' . $key] = $list;
                    }
                    foreach ($value['fieldDataText'] as $k => $v) {
                        $fieldtextdata[] = $v;
                    }
                }

                foreach ($need_handle_data as $key => $value) {
                    $db = $value['db'];
                    if ($type == 'month') {
                        $db->field('FROM_UNIXTIME(' . $value['groupTime']['name'] . ', "%Y-%m") AS orderdate');
                    } else if ($type == 'hour') {
                        $db->field('FROM_UNIXTIME(' . $value['groupTime']['name'] . ', "%Y-%m-%d %H点") AS orderdate');
                    } else {
                        $db->field('FROM_UNIXTIME(' . $value['groupTime']['name'] . ', "%Y-%m-%d") AS orderdate');
                    }
                    $db->where($value['groupTime']['name'], 'between time', [$start, $end]);
                    $model = $db
                        ->field('MIN(' . $value['groupTime']['name'] . ') AS min_startdate')
                        ->field('MAX(' . $value['groupTime']['name'] . ') AS max_startdate');
                    if (isset($value['join_arr']) && $value['join_arr']) {
                        $model = $model->join($value['join_arr']);
                    }
                    foreach ($value['fieldData'] as $field_k => $field_v) {
                        $model = $model->field($field_v);
                    }
                    $data_list = $model
                        ->where($value['whereData'])
                        ->group('orderdate')
                        ->select();
                    foreach ($data_list as $k => $v) {
                        foreach ($need_handle_field as $n_k => $n_v) {
                            $series[$n_v . '_' . $key][$v['orderdate']] = $v[$n_v];
                        }
                    }
                }
                foreach ($series as $k => &$v) {
                    $v = array_values($v);
                }
                unset($v);
                $result = array("series" => $series, 'column' => $column, 'fieldtextdata' => $fieldtextdata);
            }
            $this->success('', null, $result);
        }
    }
}
